package com.novax.ex.activity.provider.service;

import com.alibaba.fastjson.JSON;
import com.novax.ex.activity.infrastructure.entity.TaskUserProgress;
import com.novax.ex.activity.infrastructure.mapper.TaskUserProgressMapper;
import com.novax.ex.common.base.BaseMapper;
import com.novax.ex.common.base.BaseService;
import com.novax.ex.common.constant.ActivityConstants;
import com.novax.ex.common.core.redis.RedisUtil;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class TaskUserProgressService extends BaseService {

    @Resource
    private TaskUserProgressMapper taskUserProgressMapper;

    @Override
    protected BaseMapper getBaseMapper() {
        return taskUserProgressMapper;
    }

    /**
     * 通过用户ID查询用户当前任务做到了那一步
     *
     * @param uid 用户ID
     * @return 用户当前任务做到了那一步
     */
    public int findStepByUid(Long uid) {

        TaskUserProgress taskUserProgress = new TaskUserProgress();
        taskUserProgress.setUid(uid);

        TaskUserProgress result;
        Object redisUserTaskProgress = RedisUtil.get(ActivityConstants.redisType.NEW_USER + uid);
        if (Objects.isNull(redisUserTaskProgress)) {
            result = taskUserProgressMapper.selectByCondition(taskUserProgress);
            if (Objects.nonNull(result)) {
                RedisUtil.set(ActivityConstants.redisType.NEW_USER + uid, JSON.toJSONString(result), 10L, TimeUnit.MINUTES);
                return result.getStep();
            }
            return 0;
        } else {
            result = JSON.parseObject((String)redisUserTaskProgress, TaskUserProgress.class);
            return result.getStep();
        }
    }

    /**
     * 通过用户uid查询该用户对应的版本ID
     *
     * @param uid 用户ID
     * @return 版本号
     */
    public Long findVersionByUid(Long uid) {
        return taskUserProgressMapper.selectVersion(uid);
    }

    public TaskUserProgress findUserTaskProgress(Long uid) {
        TaskUserProgress taskUserProgress = new TaskUserProgress();
        taskUserProgress.setUid(uid);
        return taskUserProgressMapper.selectByCondition(taskUserProgress);
    }
}
